package net.thermetics.fx.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import net.thermetics.fx.auth.GaeUser;
import net.thermetics.fx.dal.PMF;
import net.thermetics.fx.model.Report;
import net.thermetics.fx.model.ReportVote;
import net.thermetics.fx.services.ReportService;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ReportServiceImpl implements ReportService {
	@Override
	public Report getReport(String id) {
		PersistenceManager pm = PMF.get();
		
		try {
			Key threadKey = KeyFactory.createKey(Report.class.getSimpleName(), id);
			Report thread = pm.getObjectById(Report.class, threadKey);
			pm.makePersistent(thread);
			return thread;
		}
		catch (JDOObjectNotFoundException e) {
			return null;
		}
		finally {
			pm.close();
		}
	}

	@Override
	public void deleteReport(String id) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean updateReport(Report thread) {
		PersistenceManager pm = PMF.get();
		try {
			pm.makePersistent(thread);
		}
		finally {
			pm.close();
		}
		
		return true;
	}

	@Override
	public Report createReport(String id) {
		Report report = new Report();
		report.setThreadID(id);
		Key key = KeyFactory.createKey(Report.class.getSimpleName(), id);
		report.setKey(key);
		
		PersistenceManager pm = PMF.get();
		try {
			pm.makePersistent(report);
		}
		finally {
			pm.close();
		}
		
		return report;
	}

	@Override
	public ReportVote createVote(Report report, GaeUser user) {			
		System.out.println("Creating new vote");
		ReportVote userVote = new ReportVote();
		userVote.setUserKey(user.getKey());
		//userVote.setViolation(ReportVote.NO_VIOLATION);
		report.addVote(userVote);
		return userVote;
	}

	@Override
	public Map<String, Integer> getVoteCombinations(Report report) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		List<ReportVote> votes = report.getVotes();
		
		for (ReportVote vote : votes) {
			String combo = "";
			if (vote.getAction() == null) {
				combo = "No Action";
			}
			else {
				combo = vote.getAction();
			}
			
			combo += " + " + vote.getViolation();
			
			if (combo.contains("No Violation")) {
				combo = "No Violation";
			}
			if (combo.contains("No violation selected") || vote.getViolation() == null) {
				combo = "No violation selected";
			}
			
			Integer users = map.get(combo);
			if (users == null) {
				map.put(combo, 1);
			}
			else {
				int intValue = users.intValue();
				intValue++;
				map.put(combo, intValue);
			}
		}
		
		return map;
	}

}
